Page({
  data: {
    isLogging: false
  },

  onGetUserInfo(e) {
    if (e.detail.errMsg === 'getUserInfo:ok') {
      this.login(e.detail.userInfo);
    } else {
      wx.showToast({
        title: '登录失败',
        icon: 'none'
      });
    }
  },

  login(userInfo) {
    this.setData({ isLogging: true });

    wx.cloud.callFunction({
      name: 'login',
      data: {
        userInfo: userInfo
      },
      success: (res) => {
        wx.setStorageSync('userInfo', res.result.userInfo);
        wx.setStorageSync('openid', res.result.openid);
        wx.showToast({
          title: '登录成功',
          icon: 'success'
        });
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/user/center'
          });
        }, 1500);
      },
      fail: () => {
        wx.showToast({
          title: '登录失败',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ isLogging: false });
      }
    });
  },

  showAgreement() {
    this.selectComponent('#agreementDialog').show();
  },

  hideAgreement() {
    this.selectComponent('#agreementDialog').hide();
  }
});